package cn.edu.nuc.dictProceed;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

public class BackWords extends ContextWrapper{
	private final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
			+ "/dictionary";
	private final String DATABASE_FILENAME = "dictionary.db";
	public BackWords(Context base) {
		super(base);
		// TODO Auto-generated constructor stub
	}

	private SQLiteDatabase database;

	public Cursor lookup(String abc) {
		// TODO Auto-generated method stub
		database = openDatabase();
		Cursor result = null;
		String sql = "select * from t_words where english="+"'"+abc+"'";
		result = database.rawQuery(sql, null);
//		result = database.query("t_words", new String[]{"chinese","english"}, "chinese="+abc, null, null, null, null);

		return result;
	}

	private SQLiteDatabase openDatabase() {
		try {
			String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
			File dir = new File(DATABASE_PATH);
			if (!dir.exists())
				dir.mkdir();
			if (!(new File(databaseFilename)).exists()) {
				InputStream is = getResources().getAssets().open(databaseFilename);
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[8192];
				int count = is.read(buffer);
				// while ((count = is.read(buffer)) > 0)
				while (count > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);
			return database;
		} catch (Exception e) {
		}
		return null;
	}
}
